const { Service } = require('egg')
const { tableToList, zc } = require('../utils/tools')

// eslint-disable-next-line max-len
const defaulTime = ['08:00~08:45', '08:55~09:40', '10:00~10:45', '10:55~11:40', '14:00~14:45', '14:55~15:40', '15:50~16:35', '16:45~17:30', '18:30~19:15', '19:25~20:10', '20:20~21:05', '21:15~22:00']

module.exports = class CourseService extends Service {
  /**
   * ! 学生个人课表查询:老师姓周的情况之前没有考虑
   * @param {string} term 学期
   * @return {Object} *
   */
  async table(term) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/xskb/xskb_list.do`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      headers: {
        Cookie,
        Host: 'webvpn.hnust.edu.cn',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      data: {
        cj0701id: '',
        zc: '',
        demo: '',
        xnxq01id: term,
        sfFD: '1',
        wkbkc: '1',
        kbjcmsid: '0B841F8A531A4C05BE8DB7DB4B40AEF1',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const cb = (cell, rowIndex, colIndex, $) => {
          const value = cell.text().trim().replace(/\s/g, '') // 获取单元格内容
          if (rowIndex > 0 && rowIndex <= 6 && colIndex > 0) {
            const tem = [[]]
            cell.find('.kbcontent').each((_, kbcontent) => {
              $(kbcontent).contents().each((__, e) => {
                const value_ = $(e).text().replace(/\s/g, '')
                if (value_ === '') return true // 空白单元格跳过
                if (value_.includes('-----')) tem.push([]) // 分隔线后是另一个课程
                else tem[tem.length - 1].push(value_)
                return value_
              })
            })
            return tem
          }

          return value
        }
        const tableList = tableToList(res.data.toString(), '#timetable', '', cb)
        console.log('tableList', tableList[1])
        const Ntable = {}
        const time = defaulTime // 记录每节课上课时间
        const note = tableList[tableList.length - 1][1] // 记录备注信息

        // 处理表格信息
        const period = ['', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
        for (let i = 1; i < tableList.length - 1; i++) {
          const tempNum = i * 2
          Ntable[period[tempNum]] = []
          if (tempNum > 0)Ntable[period[tempNum - 1]] = []

          for (let j = 1; j < tableList[i].length; j++) {
            const infoList = tableList[i][j]
            const tem = infoList.map((item) => {
              let [N, T, W, R] = '' // N: 课程名字，T: 课程老师，W: 课程周次，R: 课程地点，P: 课程周次
              let P = []
              if (item.length === 0) return ''
              if (item.length === 6) { // 正常情况下有六项，0. 课程名称 1. 课程老师 2. 课程周次 3. 课程地点 4. 课程时间 5. 课程专业
                N = item[0]
                T = item[1]
                W = item[2]
                R = item[4]
                const str = `${item[2].slice(0, item[2].indexOf('周')).replace(/\(/g, '')}周`
                P = zc(str)
              } else if (item.length === 5) { // 课表信息有五项，一般是缺失上课地点？照抄0052的
                N = item[0] + item[1]
                T = item[2]
                W = item[3]
                R = ''
                P = zc(item[3])
              }
              return {
                N, T, W, R, P,
              }
            }).filter((str) => str !== '')
            Ntable[period[tempNum]].push(tem)
            if (tempNum > 0)Ntable[period[tempNum - 1]].push(tem)
          }
        }

        return { table: Ntable, time, note }
      }
      catch (err) {
        console.log(err)
        throw err
      }
    }
    return { table: {}, time: [], note: [] }
  }

  /**
   * * 班级课表查询
   * @param {string} term 学期
   * @param {string} yx 院系
   * @param {string} nj 年级
   * @param {string} zy 专业
   * @param {string} name 班级名称
   * @return {Array} *
   */
  async Ctable(term, yx, nj, zy, name) {
    console.log('name', name)
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kbcx/kbxx_xzb_ifr`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        xnxqh: term,
        kbjcmsid: '94673FF3230E4769E0533C41FF0A2703',
        skyx: yx,
        sknj: nj,
        skzy: zy,
        skbjid: '',
        skbj: '',
        zc1: '',
        zc2: '',
        skxq1: '',
        skxq2: '',
        jc1: '',
        jc2: '',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#kbtable')
        return tableList
      } catch (err) {
        console.log(err)
        throw err
      }
    }
    return []
  }

  /**
   * * 教师课表查询
   * @param {string} term 学期
   * @param {string} yx 院系
   * @param {string} name 教师姓名
   * @return {Array} *
   */
  async Ttable(term, yx, name) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kbcx/kbxx_teacher_ifr`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        xnxqh: term,
        kbjcmsid: '94673FF3230E4769E0533C41FF0A2703',
        skyx: yx,
        jszc: '',
        skbjid: '',
        skjs: name,
        zc1: '',
        zc2: '',
        skxq1: '',
        skxq2: '',
        jc1: '',
        jc2: '',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#kbtable')
        return tableList
      } catch (err) {
        console.log(err)
        throw err
      }
    }
    return []
  }

  /**
   * * 教室课表查询
   * @param {string} term 学期
   * @param {string} building 教学楼
   * @param {string} name 教室名称
   * @return {Array} *
   */
  async Rtable(term, building, name) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kbcx/kbxx_classroom_ifr`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        xnxqh: term,
        kbjcmsid: '94673FF3230E4769E0533C41FF0A2703',
        skyx: '',
        xqid: '',
        jzwid: building,
        gnq: '',
        jszc: '',
        skbjid: '',
        skjs: name,
        zc1: '',
        zc2: '',
        skxq1: '',
        skxq2: '',
        jc1: '',
        jc2: '',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#kbtable')
        return tableList
      } catch (err) {
        console.log(err)
        throw err
      }
    }
    return []
  }
}
